package com.um.jdy.platform.device.manger;

import cn.hutool.core.bean.BeanUtil;
import com.um.jdy.common.charge.code.OrderCode;
import com.um.jdy.common.device.code.DeviceCode;
import com.um.jdy.common.device.entity.dto.GunDTO;
import com.um.jdy.common.device.entity.po.Gun;
import com.um.jdy.common.device.entity.po.Pile;
import com.um.jdy.common.device.entity.vo.GunVO;
import com.um.jdy.common.device.enums.DeviceEnum;
import com.um.jdy.common.device.service.GunService;
import com.um.jdy.common.device.service.PileService;
import com.um.jdy.platform.device.entity.dto.PortRestartDTO;
import com.um.jdy.platform.device.entity.vo.GunStatusNumVO;
import com.um.jdy.platform.device.entity.vo.GunStatusSummaryVO;
import com.um.jdy.platform.device.entity.vo.PageGunVO;
import com.um.jdy.rpc.factory.ServiceFactory;
import com.um.springboot.starter.entity.Page;
import com.um.springboot.starter.exception.ServiceException;
import com.um.springboot.starter.orm.entity.Response;
import com.um.springboot.starter.orm.manager.BaseCMSManager;
import com.um.springboot.starter.orm.params.PageParams;
import com.um.springboot.starter.utils.OrderUtil;
import com.um.springboot.starter.utils.ReflectUtil;
import com.um.springcloud.dubbo.cluster.DeviceKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;


/**
 * 管理类：充电枪表
 */
@Component
@Slf4j
public class GunManager extends BaseCMSManager<GunService, Gun, GunDTO, GunVO> {

    @Autowired
    PileService pileService;

    @Autowired
    ServiceFactory serviceFactory;

    /**
     * 分页查询充电枪
     *
     * @param pageParams
     * @return
     */
    public Response<Page<Gun>> getPage(@RequestBody PageParams pageParams) {
        Page<Gun> page = new Page<>();
        page.setPageNo(pageParams.getPageNo());
        page.setPageSize(pageParams.getPageSize());

        pageParams.getCondition().put("orderby","port asc");

        page = service.getPage(page,pageParams.getProperties(),pageParams.getValues(),pageParams.getOrderNames(),pageParams.getSortOns());

        return Response.success(page);
    }

    /**
     * 分页查询充电枪
     * @param pageParams
     * @return
     */
    public Response<Page<PageGunVO>> getGunPage(@RequestBody PageParams pageParams){
        Page<PageGunVO> page = new Page<>();
        page.setPageNo(pageParams.getPageNo());
        page.setPageSize(pageParams.getPageSize());

        String sqlName = "get_gun_page";
        String sqlAllName = "get_gun_count";

        page = service.getCMSViewModelPageBySqlName(page,sqlName,sqlAllName, PageGunVO.class,pageParams.getProperties(),pageParams.getValues(),
                pageParams.getRangeEntitys(),pageParams.getOrderNames(),pageParams.getSortOns());

        pageParams.getCondition().remove("g.status");//删除状态查询，统计的状态才不会变为0
        GunStatusSummaryVO summaryVO = new GunStatusSummaryVO();
        List<GunStatusNumVO> list = service.getCMSViewModelListBySqlName("get_gun_status_summary",GunStatusNumVO.class,pageParams.getProperties(),pageParams.getValues(),
                pageParams.getRangeEntitys(),new String[]{},new String[]{});
        for(GunStatusNumVO item : list){
            ReflectUtil.setValue(summaryVO,item.getStatus().toLowerCase(),item.getNum());
        }
        page.setExtraData(summaryVO);
        return Response.success(page);
    }

//    @Override
//    public Response<Gun> addEntity(GunDTO dto) {
//        Gun entity = UMBeanUtils.copyBean(dto, Gun.class);
//        String pileId = entity.getDevicePileId();
//        // TODO: 2023-05-31
////        Gun gun = service.getEntity(new String[]{"device_pile_id", "code"}, new Object[]{pileId, entity.getCode()});
////        if (gun != null) {//枪编码已存在
////            throw new ServiceException(DeviceCode.GunExist);
////        }
//
//        Pile pile = pileService.getEntity(pileId);
//        if (pile == null) {
//            throw new ServiceException(DeviceCode.DeviceCodeNotExist);
//        }
//
//        List<Gun> list = service.getList("device_pile_id", pileId);
//
//        // TODO: 2023-05-31
////        if (list.size() >= pile.getGunNum()) {//枪数量已满
////            throw new ServiceException(DeviceCode.OverGunNumber);
////        }
//
//        service.save(entity);
//        return Response.success(entity);
//
//    }

    public Response<Gun> updateEntity(String id, GunDTO dto) {

        if (null == service.getEntity( id)) {
            throw new ServiceException(DeviceCode.NoGun);
        }


        Gun gun = BeanUtil.toBean(dto, Gun.class);
        gun.setDeviceGunId(id);
        //保存充电站
        service.save(gun);
        return Response.success(gun);
    }

    public Response restart(PortRestartDTO dto) {

        Pile pile = pileService.getEntity("code",dto.getDeviceCode());
        if (pile == null) {
            return Response.failed(DeviceCode.NoDevice);
        }

        // 设备离线
        if (!DeviceEnum.DeviceStatus.Online.name().equals(pile.getDeviceStatus())) {
            return Response.failed(DeviceCode.DeviceOffline);
        }

        try {
            serviceFactory.getRpcEBoxDeviceService(pile.getProtocol()).reqRestartPort(OrderUtil.getOrderNo(),new DeviceKey(pile.getImei()),dto.getPort());
        } catch (Exception ex) {
            log.error("重启端口失败：{}",ex.getMessage());
            return Response.failed(OrderCode.RemoteStopFailure);
        }

        return Response.success();
    }


}
